import getUserTempId from "@/utils/userTempId"

import {
    requestGotoLogin,
    requestGetUserName,
    requestGetLogOut
} from "@/api"

//home模块的配置
const state = {
    userTempId: getUserTempId(),
    token: localStorage.getItem("user_token") || "",
    nickName: "",
}

const mutations = {
    SET_TOKEN_STATE(state , value){
        state.token = value
    },

    SET_USERNAME_STATE(state , value){
        state.nickName = value
    },

    SET_GETOUT_STATE(state){
        state.token = "",
        state.nickName = "",
        localStorage.removeItem("user_token")
    }
}

const actions = {
    //登录请求
    async getLoginrequest({commit}, userInfo){
        //发送登录请求
        const result = await requestGotoLogin(userInfo)
        commit("SET_TOKEN_STATE" , result.token)
        //设置到本地存储
        localStorage.setItem("user_token" , result.token)
    },


    //获取用户名
    async getUserNameRequest({commit}){
        const result  = await requestGetUserName()
        //把用户名保存到vuex
        commit("SET_USERNAME_STATE" , result.nickName)
    },

    //退出登录
    async getoutRequest({commit}){
        await requestGetLogOut()
        commit("SET_GETOUT_STATE")
    }
}

const getters = {}


//暴露模块
export default {
    namespaced: true,
    state,
    mutations,
    actions,
    getters,
}